package org.shop.controller.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Merchant;
import org.shop.entity.Orders;
import org.shop.entity.SystemMessage;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.MerchantService;
import org.shop.service.OrdersService;
import org.shop.service.SystemMessageService;
import org.shop.util.CommonUtil;
import org.shop.util.HttpClientUtil;
import org.shop.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class WebOrderController {

	private static Logger logger = LogManager.getLogger(WebOrderController.class);
	
	@Autowired
    private OrdersService ordersService;
	@Autowired
	private MerchantService merchantService;
	@Autowired
	private SystemMessageService systemMessageService;
	
 	/**
	 * 店铺获取所有订单
	 * @return
	 */
	@RequestMapping("web/getShopOrderList")
	@ResponseBody
	public Map<String, Object> getShopOrderList(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
        String currentPage = req.getParameter("offset");
        String pageSize = req.getParameter("limit");
        String orderNo = req.getParameter("orderNo");
        String userName = req.getParameter("userName");
        String userPhone = req.getParameter("userPhone");
        String goodsName = req.getParameter("goodsName");
        String orderStatus = req.getParameter("orderStatus");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime") == null ? "" : req.getParameter("endTime")+"23:59:59";
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("merchantId", ud.getMerchantId());
            paramMap.put("orderNo", orderNo);
            paramMap.put("userName", userName);
            paramMap.put("goodsName", goodsName);
            paramMap.put("userPhone", userPhone);
            paramMap.put("orderStatus", orderStatus);
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            map = ordersService.getShopOrderList(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
		return map;
	}

	
	/**
	 * 商家发送订单
	 * @return
	 */
	@RequestMapping("web/sendOrder")
	@ResponseBody
	public Map<String,Object> sendOrder(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
        String orderId = req.getParameter("orderId");
        String sendGoodsUserName = req.getParameter("sendGoodsUserName");
        String sendGoodsUserPhone = req.getParameter("sendGoodsUserPhone");
        MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//获取登录人用户信息
		try {
			Orders orders = ordersService.selectByPrimaryKey(Long.parseLong(orderId));
			if(orders==null){
				map.put("state", 0);
				map.put("msg", "发货失败");
				return map;
			}
			Merchant merchant=merchantService.selectByPrimaryKey(ud.getMerchantId());
			int random=(int)((Math.random()*9+1)*100000);
			String smsUrl=CommonUtil.getPropertiesParam("smsUrl");
			String account=CommonUtil.getPropertiesParam("account");
			String password=CommonUtil.getPropertiesParam("password");
			Map<String, Object> paramMap=new HashMap<String, Object>();
			paramMap.put("account", account);
			paramMap.put("password", password);
			paramMap.put("phone", orders.getUserPhone());
			paramMap.put("msg", "尊敬的"+orders.getUserName()+"，您在"+merchant.getMerchantName()+"购买的宝贝已经发出,送货人："+sendGoodsUserName+"，联系电话："+sendGoodsUserPhone+"，收货码："+random);
			String bodyJson=HttpClientUtil.doPostJson(smsUrl, JsonUtils.toJson(paramMap));
			String code=JsonUtils.fromJson(bodyJson).get("code").asText();
			if(code.equals("0")){
				orders.setSendGoodsUserName(sendGoodsUserName);
				orders.setSendGoodsUserPhone(sendGoodsUserPhone);
				orders.setUserGetCode(random+"");
				orders.setOrderStatus((byte)4);
				ordersService.updateByPrimaryKeySelective(orders);
				map.put("state", 1);
				map.put("msg", "发货成功");
				SystemMessage system = new SystemMessage();
				system.setOrderId(Long.parseLong(orderId));
				system.setSendId(ud.getUserId());
				system.setMessageType((byte) 2);
				system.setreceiveId(orders.getUserId());
				system.setMessageContent("您的订单号为"+orders.getOrderNo()+"的商品,由"+sendGoodsUserName.substring(0,1)+"先生/女士,电话号码为："+sendGoodsUserPhone+"开始派送,请注意查收。");
				systemMessageService.insertSelective(system);
			}else{
				map.put("state", 0);
				map.put("msg", "发货失败");
			}
		} catch(Exception e) {
			map.put("state", 0);
			map.put("msg", "发货失败");
            logger.error(e);
        }
		return map;
	}
	/**
	 * 商家订单收货
	 * @return
	 */
	@RequestMapping("web/getOrder")
	@ResponseBody
	public Map<String,Object> getOrder(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
        String orderId = req.getParameter("orderId");
        String userGetCode = req.getParameter("userGetCode");
		//获取登录人用户信息
		try {
			Orders orders = ordersService.selectByPrimaryKey(Long.parseLong(orderId));
			if(orders==null){
				map.put("state", 0);
				map.put("msg", "收货失败");
				return map;
			}else{
				if(orders.getUserGetCode().equals(userGetCode)){
					orders.setOrderStatus((byte)5);
					ordersService.updateByPrimaryKeySelective(orders);
					map.put("state", 1);
					map.put("msg", "收货成功");
				}else{
					map.put("state", 2);
					map.put("msg", "收货失败，收货码不正确");
				}
			}
		} catch(Exception e) {
			map.put("state", 0);
			map.put("msg", "收货失败");
            logger.error(e);
        }
		return map;
	}
	
	
}
